package home

import (
	"gitee.com/jikey/elk-blog/app/model"
	"gitee.com/jikey/elk-blog/app/service"
	"gitee.com/jikey/elk-blog/pkg/e"
	"gitee.com/jikey/elk-blog/pkg/response"
	"gitee.com/jikey/elk-blog/pkg/utils"
	"gitee.com/jikey/elk-blog/setting"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"html/template"
	"strconv"
)

type Message struct {
	Controller
}

// Index 留言首页
func (message *Message) Index(c *gin.Context) {
	data := make(map[string]interface{})
	pageNum, _ := strconv.Atoi(c.Query("page"))
	maps := make(map[string]interface{})

	// 获取分页数据
	page := utils.NewPagination(c.Request, service.Message.Total(maps), setting.Config.App.PageSize)
	data["page"] = template.HTML(page.Pages())
	data["list"] = service.Message.List(pageNum, setting.Config.App.PageSize, maps)
	data["link"] = service.Link.List(1, 100, "")
	data["archiveList"] = service.Article.ArticleArchiveList()
	data["articleCategory"] = service.Category.GetArticleCategoryList("4")
	data["site"] = service.System.GetSystem(1)
	data["active"] = "message"

	response.Render(c, "message/index", data)
}

// Add 新增留言
func (message *Message) Add(c *gin.Context) {
	msg := model.Message{}

	if err := c.ShouldBindJSON(&msg); err != nil {
		c.JSON(400, gin.H{
			"err": err.Error(),
		})
		return
	}

	verify := msg.Verify
	captchaId := msg.CaptchaId

	if ok := utils.Verify(captchaId, verify); !ok {
		response.JSON(c, gin.H{
			"code": 2,
			"msg":  "图片验证码错误",
		})
		return
	}

	logrus.Error("msg: ", msg)
	err := service.Message.Create(&msg)

	if err != nil {
		logrus.Error("新增留言失败: ", err)
		response.Fail(c, e.ErrorInsert)
		return
	}

	response.Success(c, msg)
}
